package com.zrrd.gmall.product.controller;

import com.zrrd.gmall.common.result.Result;
import jodd.io.FileNameUtil;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileUrl;

    //文件上传
    @PostMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws MyException, IOException {
        //声明文件存在dfs服务器中的路径（没有前缀）
        String path = null;
        //1.加载FastDFS配置文件
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        //2.非空判断
        if (configFile != null) {
            //3.初始化配置
            ClientGlobal.init(configFile);
            //4.创建上传客户端对象
            TrackerClient trackerClient = new TrackerClient();
            //5.通过客户端对象获取一个上传连接对象
            TrackerServer trackerServer = trackerClient.getConnection();
            //6.创建执行上传的对象
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
            //7.进行文件上传
            path = storageClient1.upload_appender_file1(file.getBytes(),
                    FileNameUtil.getExtension(file.getOriginalFilename()), null);
        } else {
            return Result.fail("初始化文件服务器失败");
        }
        log.info("文件上传成功===>" + fileUrl + path);
        //给前端返回文件在fastDFS服务器中完整的路径
        return Result.ok(fileUrl + path);
    }
}
